import threading

_request_local = threading.local()

class PortBasedDatabaseMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        port = request.META.get('SERVER_PORT')
        print(port)
        if port == '8185':
            _request_local.db_alias = 'db8085'
        elif port == '8187':
            _request_local.db_alias = 'db8087'
        elif port == '8188':
            _request_local.db_alias = 'db8088'
        elif port == '8189':
            _request_local.db_alias = 'db8089'
        else:
            _request_local.db_alias = 'default'

        response = self.get_response(request)

        return response

def get_db_alias():
    return getattr(_request_local, "db_alias", "default")
